<?php
/**
 * 积分抽奖管理
 */
namespace Admin\Controller;
use Admin\BaseController;
use Common\Model\PointLotteryModel;
use Common\Model\SignLuckyModel;
use Think\Page;
class PointLotteryController extends BaseController{
	//活动状态
	const STATUS_PREPARE	=0;//待上线
	const STATUS_ONLINE		=1;//线上
	const STATUS_FINISH		=2;//已结束

	public function timingNew(){
		$period = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='TIMING_LOTTERY_PERIOD'")->getField("cfgValue");
		$periods = array();
		if($period){
			for($i=$period;$i>=1;$i--){
				$periods[$i]=$i;
			}
		}
		$this->smarty->assign('period',$periods);

		$prizeType = getContentTypeKv();
		$this->smarty->assign('prizeType',$prizeType);

		$userLevelRequire = getLevelKv();
		$this->smarty->assign('userLevelRequire',$userLevelRequire);
		$this->smarty->display('PointLottery/timingNew.html');
	}

	public function timingEdit(){
		$id=I('get.id',0,'int');
		if($id<1){
			$this->error("请指定目标");
		}
		$lotteryM=M('point_lottery',null,DB_MAIN_CFG);
		$lotteryInfo=$lotteryM->where("id={$id}")->find();
		if(!$lotteryInfo){
			$this->error("请指定目标");
		}

		$period = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='TIMING_LOTTERY_PERIOD'")->getField("cfgValue");
		$periods = array();
		if($period){
			for($i=$period;$i>=1;$i--){
				$periods[$i]=$i;
			}
		}
		$this->smarty->assign('period',$periods);

		$prizeType = getContentTypeKv();
		$this->smarty->assign('prizeType',$prizeType);

		$userLevelRequire = getLevelKv();
		$this->smarty->assign('userLevelRequire',$userLevelRequire);

		$marqueePic=explode(',',$lotteryInfo['marqueePic']);

		$this->smarty->assign('marquee',$marqueePic);
		$this->smarty->assign('obj',$lotteryInfo);
		$this->smarty->display('PointLottery/timingNew.html');


	}

	public function timingUpdate(){
		$id=I('post.id',0,'int');
		$marquee=I('post.marquee');
		if(!$marquee){
			$this->ajaxReturn( array('status'=>1, 'msg'=> '请选择详情图片') );
//			$this->error("请选择详情图片");
		}
		foreach($marquee as $k=>$v){
			if(strlen($v)<5){
				unset($marquee[$k]);
			}
		}
		$maxPeriod = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='TIMING_LOTTERY_PERIOD'")->getField('cfgValue');
		$data = array(
			'period'			=> I('post.period',$maxPeriod),
			'title'				=> I('post.title'),
			'userLevelRequire'	=> I('post.userLevelRequire',0,'int'),
			'points'			=> I('post.points',0,'int'),
			'originalPrice'		=> I('post.originalPrice',0,'float'),
			'quota'				=> I('post.quota',0,'int'),
			'prizeNum'			=> I('post.prizeNum',0,'int'),
			'prizeType'			=> I('post.prizeType',1,'int'),
			'beginShowTimestamp'=> strtotime(I('post.beginShowTimestamp')),
			'beginTime'			=> strtotime(I('post.beginTime')),
//			'endShowTimestamp'	=> strtotime(I('post.endShowTimestamp')),
			'endTime'			=> strtotime(I('post.endTime')),
			'marqueePic'		=> implode(',',$marquee),
			'listPic'			=> I('post.listPic'),
			'content'			=> htmlspecialchars_decode(I('post.content')),
			'finishType'		=> PointLotteryModel::POINTLOTTERY_TIMING,
			'status'			=> PointLotteryModel::LOTTERY_RESULT_WAIT
		);

		$lotteryM=M('point_lottery',null,DB_MAIN_CFG);

		if($id==0){//新增
			$id=$lotteryM->add($data);
		}else{//修改
			$lotteryM->where("id={$id}")->save($data);
		}
		$this->ajaxReturn(array('status' =>0, 'msg'=> '操作完成','id'=>$id));

	}
	/**
	 * 已上线活动
	 * Author: shijy
	 */
	private function timingListBase($processStatus){
		$where='1 and finishType=1';
		$title=I('get.title',null);
		if($title){
			$where .=" and title like '%{$title}%'";
		}
		$nowTime=time();
		switch($processStatus){
			case self::STATUS_PREPARE:
				$where .=" and {$nowTime} < beginTime";
				break;
			case self::STATUS_ONLINE:
				$where .=" and {$nowTime} between beginTime and endTime ";
				break;
			case self::STATUS_FINISH:
				$where .=" and {$nowTime} >= endTime";
				break;
		}

		$lotteryM=M("point_lottery",null,DB_MAIN_CFG);
		$order = "endTime desc,beginTime desc";

		$count = $lotteryM->where($where)->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty,$Page);

		$list = $lotteryM->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();

		$this->smarty->assign('limit',$limit);
		$this->smarty->assign('title',$title);
		$this->smarty->assign('list',$list);

		$this->smarty->display('PointLottery/timingIndex.html');
	}

	public function timingOnline(){
		$this->timingListBase(self::STATUS_ONLINE);
	}

	public function timingFinish(){
		$this->timingListBase(self::STATUS_FINISH);
	}

	public function timingPrepare(){
		$this->timingListBase(self::STATUS_PREPARE);
	}

	public function timingDel(){
		$id=I('get.id',0,'int');
		if($id<1){
			$this->error("请指定目标");
		}
		$lotteryM=M('point_lottery',null,DB_MAIN_CFG);
		$lotteryInfo=$lotteryM->where("id={$id}")->find();
		if(!$lotteryInfo){
			$this->error("请指定目标");
		}
		if(time()>$lotteryInfo['beginShowTimestamp']){
			$this->error("活动已经上线，不可删除");
		}
		$lotteryM->where("id={$id}")->delete();
		$this->success("指定对象已经成功删除");

	}

	public function timingMember(){
		$where = "uid!=0 and type=".PointLotteryModel::POINTLOTTERY_TIMING;
		$id=I('get.id',0,'int');
		if($id){
			$where .= " and lotteryID={$id}";
		}
		//时间筛选
		$startDate = I('get.startDate',null);
		$endDate = I('get.endDate',null);

		$startTime = strtotime($startDate);
		$endTime = strtotime($endDate);
		if($startTime){
			$where .= " and addTime >= {$startTime}";
		}else if($endTime){
			$where .= " and addTime <= {$endTime}";
		}

		$keyword=I('get.keyword',null);
		if($keyword){
			$where .=" and concat(title,nickname,realName,bindPhone) like '%{$keyword}%'";
		}

		$result = I('get.result',0,'int');
		if($result){
			$where .=" and result=".PointLotteryModel::LOTTERY_RESULT_WIN;
		}

		$joinM = M("point_lottery_join",null,DB_MAIN_CFG);

		$count = $joinM->where($where)->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty,$Page);

		$list = $joinM->where($where)->order('addTime desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

		$this->smarty->assign('limit',$limit);
		$this->smarty->assign('keyword',$keyword);
		$this->smarty->assign('startDate',$startDate);
		$this->smarty->assign('endDate',$endDate);
		$this->smarty->assign('list',$list);

		$this->smarty->display('PointLottery/timingMember.html');

	}

	//满员抽奖基础列表
	public function fullListBase($processStatus){
		$where='1 and finishType='.PointLotteryModel::POINTLOTTERY_FULL;
		$keyword = I('get.keyword',null);
		if($keyword){
			$where .=" and title like '%{$keyword}%'";
		}

		$nowTime = time();
		switch($processStatus){
			case self::STATUS_PREPARE:
				$where .=" and {$nowTime} < beginTime";
				break;
			case self::STATUS_ONLINE:
				$where .=" and {$nowTime} between beginTime and endTime and joinPeople < fullNumber";
				break;
			case self::STATUS_FINISH:
				$where .=" and ({$nowTime} >= endTime or joinPeople >= fullNumber)";
				break;
		}

		$lotteryM = M('point_lottery',null,DB_MAIN_CFG);

		$count = $lotteryM->where($where)->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$page = new Page($count,$limit);
		fetchPage($this->smarty,$page);

		$list = $lotteryM->where($where)->order('endTime desc,beginTime desc')->limit($page->firstRow . ',' .$page->listRows)->select();

		$this->smarty->assign('limit',$limit);
		$this->smarty->assign('title',$keyword);
		$this->smarty->assign('list',$list);
		$this->smarty->display('PointLottery/fullIndex.html');
	}

	public function fullOnline(){
		$this->fullListBase(self::STATUS_ONLINE);

	}

	//新增满员抽奖
	public function fullNew(){
		$period = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='FULL_LOTTERY_PERIOD'")->getField("cfgValue");
		$periods = array();
		if($period){
			for($i=$period;$i>=1;$i--){
				$periods[$i]=$i;
			}
		}
		$this->smarty->assign('period',$periods);

		$prizeType = getContentTypeKv();
		$this->smarty->assign('prizeType',$prizeType);

		$userLevelRequire = getLevelKv();
		$this->smarty->assign('userLevelRequire',$userLevelRequire);
		$this->smarty->display('PointLottery/fullNew.html');
	}

	//编辑满员抽奖（修改）
	public function fullEdit(){
		$id=I('get.id',0,'int');
		if($id<1){
			$this->error("请指定目标");
		}
		$lotteryM=M('point_lottery',null,DB_MAIN_CFG);
		$lotteryInfo=$lotteryM->where("id={$id}")->find();
		if(!$lotteryInfo){
			$this->error("请指定目标");
		}

		$period = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='FULL_LOTTERY_PERIOD'")->getField("cfgValue");
		$periods = array();
		if($period){
			for($i=$period;$i>=1;$i--){
				$periods[$i]=$i;
			}
		}
		$this->smarty->assign('period',$periods);

		$prizeType = getContentTypeKv();
		$this->smarty->assign('prizeType',$prizeType);

		$userLevelRequire = getLevelKv();
		$this->smarty->assign('userLevelRequire',$userLevelRequire);
		$marqueePic=explode(',',$lotteryInfo['marqueePic']);

		$this->smarty->assign('marquee',$marqueePic);
		$this->smarty->assign('obj',$lotteryInfo);
		$this->smarty->display('PointLottery/fullNew.html');
	}

	//新增或修改满员抽奖
	public function fullUpdate(){
		$id = I('post.id',0,'int');
		$marquee  = I('post.marquee');
		if(!$marquee){
			$this->ajaxReturn(array('status' =>1,'msg' => '请选择详情图片'));
		}
		foreach($marquee as $k=>$v){
			if(strlen($v)<5){
				unset($marquee[$k]);
			}
		}

		$period = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='FULL_LOTTERY_PERIOD'")->getField('cfgValue');

		$data=array(
			'period'			=> I('post.period',$period),
			'title'				=> I('post.title'),
			'userLevelRequire'	=> I('post.userLevelRequire',0,'int'),
			'points'			=> I('post.points',0,'int'),
			'originalPrice'		=> I('post.originalPrice',0,'float'),
			'fullNumber'		=> I('post.joinPeopleNum',0,'int'),			//满员人数
			'quota'				=> I('post.quota',1,'int'),
			'prizeNum'			=> I('post.prizeNum',0,'int'),
			'prizeType'			=> I('post.prizeType',1,'int'),
			'beginShowTimestamp'=> strtotime(I('post.beginShowTimestamp')),
			'beginTime'			=> strtotime(I('post.beginTime')),
			'endTime'			=> strtotime(I('post.endTime')),
			'marqueePic'		=> implode(',',$marquee),
			'listPic'			=> I('post.listPic'),
			'content'			=> htmlspecialchars_decode(I('post.content')),
			'finishType'		=> PointLotteryModel::POINTLOTTERY_FULL,
			'status'			=> PointLotteryModel::LOTTERY_RESULT_WAIT
		);
		if($data['fullNumber'] <= 0){
			$this->ajaxReturn(array('status' =>1,'msg' => '请输入满员人数'));
		}

		$lotteryM=M('point_lottery',null,DB_MAIN_CFG);
		if($id==0){//新增
			$id = $lotteryM->add($data);
		}else{//修改
			$lotteryM->where("id={$id}")->save($data);
		}
		$this->ajaxReturn(array('status' =>0,'msg' => '操作完成','id'=>$id));
	}

	public function fullFinish(){
		$this->fullListBase(self::STATUS_FINISH);
	}

	public function fullPrepare(){
		$this->fullListBase(self::STATUS_PREPARE);
	}
	//满员抽奖参与记录
	public function fullMember(){
		$id = I('get.id',0,'int');
		$where = "uid!=0 and type=".PointLotteryModel::POINTLOTTERY_FULL;
		if($id){
			$where .= " and lotteryID={$id}";
		}

		$keyword = I('get.keyword',null);
		if($keyword){
			$where .=" and concat(title,nickname,realName,bindPhone) like '%{$keyword}%'";
		}

		//时间筛选
		$startDate = I('get.startDate',null);
		$endDate = I('get.endDate',null);

		$startTime = strtotime($startDate);
		$endTime = strtotime($endDate);
		if($startTime){
			$where .= " and addTime >= {$startTime}";
		}else if($endTime){
			$where .= " and addTime <= {$endTime}";
		}

		$result = I('get.result',0,'int');
		if($result){
			$where .=" and result=".PointLotteryModel::LOTTERY_RESULT_WIN;
		}

		$joinM = M("point_lottery_join",null,DB_MAIN_CFG);

		$count = $joinM->where($where)->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty,$Page);

		$list = $joinM->where($where)->order('addTime desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

		$this->smarty->assign('limit',$limit);
		$this->smarty->assign('startDate',$startDate);
		$this->smarty->assign('endDate',$endDate);
		$this->smarty->assign('keyword',$keyword);
		$this->smarty->assign('list',$list);

		$this->smarty->display('PointLottery/fullMember.html');
	}
	//删除
	public function fullDel(){
		$id=I('get.id',0,'int');
		if($id<1){
			$this->error("请指定目标");
		}
		$lotteryM=M('point_lottery',null,DB_MAIN_CFG);
		$lotteryInfo=$lotteryM->where("id={$id}")->find();
		if(!$lotteryInfo){
			$this->error("请指定目标");
		}
		if(time()>$lotteryInfo['beginShowTimestamp']){
			$this->error("活动已经上线，不可删除");
		}
		$lotteryM->where("id={$id}")->delete();
		$this->success("指定对象已经成功删除");
	}

	//抽奖记录详情
	public function lotteryInfo(){
		$id= I('get.id',0,'intval');
		if(!$id){
			$this->error("请指定目标");
		}
		$joinM = M('point_lottery_join',null,DB_MAIN_CFG);
		$lotteryM = M('point_lottery',null,DB_MAIN_CFG);
		$moneyM = M('u_money_log',null,DB_MAIN_CFG);

		$info = $joinM->where("id={$id}")->find();
		if($info){
			$totalTimes = $joinM->where("uid={$info['uid']}")->count();			//抽奖总参与次数
			$payPoints = $lotteryM->where("id={$info['lotteryID']}")->getField('points');		//本次抽奖消耗积分
			$lastTakeTime = $joinM->where("uid={$info['uid']}")->order('addTime desc')->getField('addTime');		//上次抽奖时间
			$lotteryTimes = $joinM->where("uid={$info['uid']} and result=".PointLotteryModel::LOTTERY_RESULT_WIN)->count();		//中奖次数
			if($lotteryTimes>0){
				$lastLotteryTime = $joinM->where("uid={$info['uid']} and result=".PointLotteryModel::LOTTERY_RESULT_WIN)->order('addTime desc')->getField('addTime');//上次中奖时间
				$lastLotteryTime = date('Y-m-d H:i',$lastLotteryTime);
			}else{
				$lastLotteryTime ="该用户还未中奖";
			}

			$list = $joinM->where("uid={$info['uid']}")->select();
			$totalPayPoints=0;
			foreach($list as $val){
				$points = $lotteryM->where("id={$val['lotteryID']}")->getField('points');
				$totalPayPoints += $val['exchangeNum']*$points;			//抽奖总消耗积分
			}
			$uinfo = M('u_user_base',null,DB_MAIN_CFG)->where("uid={$info['uid']}")->field('userTag,level')->find();
			$userTag = getUTagKv();
			$lastPayTime = $moneyM->where("uid={$info['uid']} and addOrReduce=2")->order('addTime desc')->getField('addTime');	//上次消费时间
			$totalPayMoney=0;
			if(!$lastPayTime){
				$lastPayTime ="该用户还未有消费记录";
			}else{
				$lastPayTime = date('Y-m-d H:i',$lastPayTime);
				$payInfo = $moneyM->where("uid={$info['uid']} and addOrReduce=2")->field('changeVal')->select();
				foreach($payInfo as $val){
					$totalPayMoney +=$val['changeVal'];
				}
			}
			$data = array(
				'realName'			=> $info['realName'],
				'bindPhone'			=> $info['bindPhone'],
				'userTagHtml'		=> $userTag[$uinfo['userTag']],
				'level'				=> $uinfo['level'],
				'totalTimes'		=> $totalTimes,
				'totalPayPoints'	=> $totalPayPoints,
				'payPoints'			=> $payPoints,
				'lotteryTimes'		=> $lotteryTimes,
				'lastTakeTime'		=> date('Y-m-d H:i',$lastTakeTime),
				'lastLotteryTime'	=> $lastLotteryTime,
				'totalPayMoney'		=> $totalPayMoney,
				'lastPayTime'		=> $lastPayTime,
			);
			$this->ajaxReturn($data);
		} else{
			$this->ajaxReturn(array('status' =>1,'msg'=>'该条数据不存在，请刷新重试'));
		}
	}
	//填写待上线活动中奖名单
	public function writeWinList(){
		$dataFailure['status']=1;
		$dataSuccess['status'] = 0;
		$id=I('get.id',0,'intval');
		$info= M('point_lottery',null,DB_MAIN_CFG)->where("id={$id}")->field('finishType,prizeNum')->find();

		$realName = $_GET['realName'];
		$bindPhone = $_GET['bindPhone'];

		$phone = implode(',',$bindPhone);
		$res = M('u_user_base',null,DB_MAIN_CFG)->where("bindPhone in ({$phone})")->field('bindPhone')->select();

		if($res){
			foreach($res as $val){
				$userPhone[] = $val['bindPhone'];
			}
			foreach($bindPhone as $k =>$value){
				foreach($userPhone as $v){
					if($v == $value){
						$dataSuccess['id'][] = $k+1;
						$dataSuccess['tip'] = "手机号码已绑定用户";
					}
				}
			}
		}
		$joinM = M('point_lottery_join',null,DB_MAIN_CFG);
		$list = $joinM->where("uid=0 and lotteryID={$id}")->field("id")->select();
		foreach($list as $v){
			$idStr[] = $v['id'];
		}
		foreach($realName as $key => $val){
			$data = array(
				'type'			=> $info['finishType'],
				'lotteryID'		=> $id,
				'uid'			=> 0,
				'realName'		=> $val,
				'bindPhone'		=> $bindPhone[$key],
				'result'		=> PointLotteryModel::LOTTERY_RESULT_WIN,
			);
			if(count($idStr) == $info['prizeNum']){
				$tmp = $joinM->where("lotteryID={$id} and uid=0 and id={$idStr[$key]}")->save($data);
			} else if(count($idStr) < $info['prizeNum'] && count($idStr)>0){
				if(count($idStr) > $key){
					$tmp = $joinM->where("lotteryID={$id} and uid=0 and id={$idStr[$key]}")->save($data);
				} else{
					$tmp = $joinM->add($data);
				}

			} else if(count($idStr) > $info['prizeNum']){
				$tmp = $joinM->where("lotteryID={$id} and uid=0 and id={$idStr[$key]}")->save($data);
			}
			else {
				$tmp = $joinM->add($data);
			}
			if($tmp === false){
				$dataFailure['msg'] = "数据保存失败";
				$dataFailure['id'] = $key+1;
				$this->ajaxReturn($dataFailure);
			}
		}
		if(count($idStr) > $info['prizeNum']){
			$len = count($idStr);
			for($i=$info['prizeNum'];$i<$len;$i++){
				$joinM->where("lotteryID={$id} and uid=0 and id={$idStr[$i]}")->delete();
			}
		}

		$dataSuccess['msg'] = "保存成功";
		$this->ajaxReturn($dataSuccess);
	}
	//获取 待上线中奖名单列表
	public function getNameList(){
		$id = I('get.id',0,'intval');
		$prizeNum = M('point_lottery',null,DB_MAIN_CFG)->where("id={$id}")->getField('prizeNum');
		$this->smarty->assign('prizeNum',$prizeNum);

		$info = M('point_lottery_join',null,DB_MAIN_CFG)->where("uid=0 and lotteryID={$id}")->field('realName,bindPhone')->select();
		$this->smarty->assign('obj',$info);

		$html = $this->smarty->fetch('PointLottery/writeNameList.html');
		$this->ajaxReturn($html);
	}

	//编辑期数
	public function periodEdit(){
		$type = I('get.type',1,'intval');
		$this->smarty->assign('type',$type);

		if($type==PointLotteryModel::POINTLOTTERY_TIMING){
			$period = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='TIMING_LOTTERY_PERIOD'")->getField("cfgValue");
		} else{
			$period = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='FULL_LOTTERY_PERIOD'")->getField("cfgValue");
		}
		$periods = array();
		if($period){
			for($i=$period;$i>=1;$i--){
				$periods[$i]=$i;
			}
		}

		$this->smarty->assign('periods',$periods);
		$this->smarty->assign('period',$period);

		$this->smarty->display('PointLottery/period.html');
	}
	//期数更新
	public function periodUpdate(){
		$type = I('get.type',1,'intval');
		$period = I('get.period',1,'intval');
		$configM = M('cfg_config',null,DB_MAIN_CFG);

		if($type == PointLotteryModel::POINTLOTTERY_TIMING){
			$tmp = $configM->where("cfgName='TIMING_LOTTERY_PERIOD'")->setField('cfgValue',$period);
		} else {
			$tmp = $configM->where("cfgName='FULL_LOTTERY_PERIOD'")->setField('cfgValue',$period);
		}
		if($tmp ===false) $status = 1;
		else $status =0;
		$this->ajaxReturn($status);
	}

	//积分抽奖
	public function dialLottery(){
		$type = C('ELEMENT_TYPE');
		$this->smarty->assign('type',$type);
		$cardM = M("card_base_info",null,DB_MAIN_CFG);
		$cardInfo = $cardM->where("stock > 0")->field('id,title')->select();
		$cardID = array(); $cardTitle = array();
		foreach($cardInfo as $val){
			$cardID[] = $val['id'];
			$cardTitle[] = $val['title'];
		}
		$this->smarty->assign('cardID',$cardID);
		$this->smarty->assign('cardTitle',$cardTitle);

		$data = M('lucky_prize',null,DB_MAIN_CFG)
			->field("lucky_prize.*,elect_card_base_info.title")
			->join("left join elect_card_base_info on lucky_prize.extra = elect_card_base_info.id")
			->where("type=".SignLuckyModel::PRIZE_TYPE_DIAL_POINT)
			->order("lucky_prize.id ASC")
			->select();
		$this->smarty->assign('obj',$data);

		$this->smarty->assign('num',5);//配置中奖项数量
		$this->smarty->display("PointLottery/dialLottery.html");
	}
	//积分抽奖前端页面配置
	public function setPage(){
		$info = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName like 'POINT_LOTTERY_DIAL_%'")->getField('cfgName,cfgValue',true);
		$this->smarty->assign('data',$info);

		$this->smarty->display("PointLottery/dialPageSet.html");
	}
	//保存页面配置
	public function savePageSet(){
		$switch = I('get.switch',0,'int');	//功能控制开关
		$pageImg = I('get.pagePic');		//大转盘页面底图
		$rule = I('get.rule');				//抽奖规则
		$basePoint = I('get.basePoint');	//消耗积分
		$prizeImg = I('get.prizePic');		//奖品说明页面底图

		if($switch==1 && (!$pageImg || !$rule || !$basePoint || !$prizeImg)){
			$this->ajaxReturn(array('status'=>1,'msg'=>'配置数据填写不完整'));
		}

		$data = array(
			array(
				'cfgName'	=> 'POINT_LOTTERY_DIAL_PAGE_IMG',
				'cfgValue'	=> $pageImg,
				'desc'		=> '大转盘页面底图'
			),
			array(
				'cfgName'	=> 'POINT_LOTTERY_DIAL_PRIZE_IMG',
				'cfgValue'	=> $prizeImg,
				'desc'		=> '奖品说明页面底图'
			),
			array(
				'cfgName'	=> 'POINT_LOTTERY_DIAL_RULE',
				'cfgValue'	=> $rule,
				'desc'		=> '积分抽奖游戏规则'
			),
			array(
				'cfgName'	=> 'POINT_LOTTERY_DIAL_BASE_POINT',
				'cfgValue'	=> $basePoint,
				'desc'		=> '积分抽奖消耗积分'
			),
			array(
				'cfgName'	=> 'POINT_LOTTERY_DIAL_SWITCH',
				'cfgValue'	=> $switch,
				'desc'		=> '积分抽奖功能开关'
			)
		);

		$configM = M('cfg_config',null,DB_MAIN_CFG);
		$info = $configM->where("cfgName like 'POINT_LOTTERY_DIAL_%'")->select();
		if(!$info){
			$res = $configM->addAll($data);
			if($res === false){
				$this->ajaxReturn(array('status'=>1,'msg'=>'保存失败，请重试'));
			} else{
				S('pointDialLotterySwitch',$switch);
			}
		} else{
			foreach ($info as $key => $val){
				foreach ($data as $k => $v){
					if($val['cfgName'] == $v['cfgName']){
						if($val['cfgValue'] != $v['cfgValue']){
							$res = $configM->where("cfgName = '{$val['cfgName']}'")->save($v);
							if($res === false){
								$this->ajaxReturn(array('status'=>1,'msg'=>$v['desc'].'保存失败，请重试'));
							}
							if($res !== false && $val['cfgName'] == 'POINT_LOTTERY_DIAL_SWITCH'){
								S('pointDialLotterySwitch',$switch);
							}
						}
						break;
					}
				}
			}
		}
		$this->ajaxReturn(array('status'=>0,'msg'=>'保存成功'));
	}

	//大转盘抽奖中奖记录
	public function prizeLog(){
		$keyword = I('get.keyword',null);
		$prizeRank = I('get.prizeRank',0,'int');
		$export	=I('get.export',0,'int');
		$type = I('get.type',0,'int');
		$where = "1 and type={$type}";
		if($keyword && $keyword != "undefined"){
			if(is_numeric($keyword)){
				$where .= " and u_lucky_log.bindPhone like '%{$keyword}%' ";
			} else{
				$where .= " and u_lucky_log.realName like '%{$keyword}%' ";
			}
		}

		if($prizeRank > 0){
			$where .= " and prizeRank = {$prizeRank}";
		} else{
			$where .= " and prizeRank > 0";
		}

		$luckyM =  M('u_lucky_log',null,DB_MAIN_CFG);
		$rankOption = SignLuckyModel::getLuckyPrizeStatus();
		unset($rankOption[0]);
		$status = SignLuckyModel::getPrizeAcceptStatus();
		if($export){
			ini_set('memory_limit', '512M');
			$list = $luckyM
				->join('u_user_base ON u_lucky_log.uid = u_user_base.uid')
				->field('u_lucky_log.*,u_user_base.province,u_user_base.city,u_user_base.district,u_user_base.street,u_user_base.address')
				->order('id DESC')
				->where($where)
				->select();
			$uid = array();
			foreach ($list as $v){
				$uid[] = $v['uid'];
			}
			$uid = array_unique($uid);
			$info = array();
			foreach ($uid as $key=>$val){
				foreach ($list as $v){
					if($val == $v['uid']){
						$info[$key]['uid'] = $val;
						$regionKv = include_once(WEB_ROOT.'/data/area_info/'.$v['province'].'.php');
						$info[$key]['address'] = $regionKv[$v['province']]['name']
							.'.'.$regionKv[$v['city']]['name']
							.'.'.$regionKv[$v['district']]['name']
							.'.'.$regionKv[$v['street']]['name']
							.'.'.$v['address'];
						break;
					}
				}
			}

			$data = array();
			foreach ($list as $key => $val){
				$data[$key]['addTime'] = date('Y-m-d H:i:s',$val['addTime']);
				$data[$key]['realName'] = $val['realName'];
				$data[$key]['bindPhone'] = $val['bindPhone'];
				$data[$key]['prizeRank'] = $rankOption[$val['prizeRank']];
				$data[$key]['prizeName'] = str_replace('<br/>',',',$val['prizeNote']);
//				$data[$key]['prizeName'] = explode('<br/>',$val['prizeNote'])[0];
				foreach ($info as $v){
					if($val['uid'] == $v['uid']){
						$data[$key]['address'] = $v['address'];
						break;
					}
				}
				$data[$key]['status'] = $status[$val['status']];

			}
			exportExcel($data, array('中奖时间','用户名称','手机号码','中奖等级','奖品说明','收货地址','发货状态'),'中奖名单_'.date('Ymd',time()));
			exit;
		} else{
			$count = $luckyM->where($where)->count();
			$limit = I('get.limit',10,'int');	//每页显示条数
			$Page = new Page($count,$limit);
			fetchPage($this->smarty,$Page);

			$list = $luckyM
				->join('u_user_base ON u_lucky_log.uid = u_user_base.uid')
				->field('u_lucky_log.*,u_user_base.province,u_user_base.city,u_user_base.district,u_user_base.street,u_user_base.address')
				->where($where)
				->order('id DESC')
				->limit($Page->firstRow . ',' . $Page->listRows)
				->select();
			$uid = array();
			foreach ($list as $v){
				$uid[] = $v['uid'];
			}
			$uid = array_unique($uid);
			$info = array();
			foreach ($uid as $key=>$val){
				foreach ($list as $v){
					if($val == $v['uid']){
						$info[$key]['uid'] = $val;
						$regionKv = include_once(WEB_ROOT.'/data/area_info/'.$v['province'].'.php');
						$info[$key]['address'] = $regionKv[$v['province']]['name']
							.'.'.$regionKv[$v['city']]['name']
							.'.'.$regionKv[$v['district']]['name']
							.'.'.$regionKv[$v['street']]['name']
							.'.'.$v['address'];
						break;
					}
				}
			}

			foreach ($list as $key => $val){
				foreach ($info as $v){
					if($val['uid'] == $v['uid']){
						$list[$key]['address'] = $v['address'];
						break;
					}
				}
				$list[$key]['prizeRank'] = $rankOption[$val['prizeRank']];
				$list[$key]['prizeName'] = $val['prizeNote'];
				$list[$key]['statusText'] = $status[$val['status']];
			}
			$this->smarty->assign('limit',$limit);
			$this->smarty->assign('data',$list);
			$this->smarty->assign('keyword',$keyword);
			$this->smarty->assign('selectedRank',$prizeRank);
			$this->smarty->assign('rankOption',$rankOption);

			if($type == SignLuckyModel::PRIZE_TYPE_DIAL_POINT){
				$this->smarty->display('PointLottery/dialLotteryLog.html');
			} elseif($type == SignLuckyModel::PRIZE_TYPE_SIGN_LUCKY){
				$this->smarty->display('Sign/luckyRecord.html');
			}

		}

	}
	//更改奖品发货状态
	public function updatePrizeStatus(){
		$id = I('get.id',0,'int');
		$status = I('get.status',3,'int');
		if(!$id || $id <=0){
			$this->ajaxReturn(array('status'=>0,'msg'=>'未接收到记录ID，请联系管理员处理'));
		}
		if($status < SignLuckyModel::PRIZE_ACCEPT_STATUS_DID || $status > SignLuckyModel::PRIZE_ACCEPT_STATUS_NO){
			$this->ajaxReturn(array('status'=>0,'msg'=>'操作出错，请联系管理员处理'));
		}elseif ($status == SignLuckyModel::PRIZE_ACCEPT_STATUS_DID){
			$updateStatus = SignLuckyModel::PRIZE_ACCEPT_STATUS_NO;
			$note = "未发货";
		}elseif ($status == SignLuckyModel::PRIZE_ACCEPT_STATUS_NO){
			$updateStatus = SignLuckyModel::PRIZE_ACCEPT_STATUS_DID;
			$note = "已发货";
		}
		$res = M('u_lucky_log',null,DB_MAIN_CFG)->where("id = {$id}")->setField('status',$updateStatus);
		if($res !== false){
			$this->ajaxReturn(array('status'=>$updateStatus,'msg'=>'修改状态成功','note'=>$note));
		} else{
			$this->ajaxReturn(array('status'=>0,'msg'=>'状态修改失败'));
		}
	}
}
